<template>
  <div class="box">
    <div class="header-box">
      <a-alert type="warning">
        <template #description>
          <p>
            1、招商团队需要手动创建，主要可以用来团队统计招商数据，并且可以关联不同的佣金提成模板。
          </p>
          <p>
            2、可以是根据不同的渠道或者不同区域去创建，也可以根据不同的招商专员去创建，但只有招商团队可以关联招商专员。
          </p>
          <p>3、修改佣金模板，会立刻生效，影响后续的结算提成数据。</p>
        </template>
      </a-alert>
    </div>

    <a-table
      :dataSource="dataList"
      :columns="columns"
      :loading="loading"
      rowKey="id"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form layout="vertical">
              <a-row :gutter="8" :wrap="true" type="flex">
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                      placeHolder="搜索团队名称"
                      v-model:value="searchParams.name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                      placeHolder="搜索招商经理"
                      v-model:value="searchParams.leader_name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                      style="width: 100%"
                      placeholder="请选择佣金模板"
                      v-model:value="searchParams.template_id"
                      :options="commissionTemplateOptions"
                      :allowClear="true"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                      style="width: 100%"
                      placeholder="请选择项目"
                      v-model:value="searchParams.village_id"
                      :options="villageOptions"
                      :allowClear="true"
                    />
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>
                <a-col style="margin-left: auto">
                  <a-button type="primary" @click="addTeam">+新增团队</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key == 'team_user_count'">
          <a-button type="link" @click="showTeamUser(record)">{{
            record.team_user_count
          }}</a-button>
        </template>
        <template v-if="column.key === 'commission_template'">
          <a-space>
            <span>{{
              record?.template_id
                ? record?.commission_template?.name || "--"
                : "--"
            }}</span>
            <a-button type="link" @click.stop="editTemplate(record)">
              <FormOutlined />
            </a-button>
          </a-space>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" @click.stop="handleAddTeamPersonnel(record)">
            新增人员
          </a-button>
          <a-button type="link" @click.stop="editTeam(record)"> 编辑 </a-button>
          <a-button
            type="link"
            danger
            @click.stop="handleRemoveTeamPersonnel(record)"
            >移除人员</a-button
          >
          <a-button type="link" danger @click.stop="handleDelete(record)"
            >删除</a-button
          >
        </template>
      </template>
    </a-table>

    <!--  新增&编辑团队  -->
    <AddBusinessTeam
      :visible="addVisible"
      :villageOptions="villageOptions"
      :id="editId"
      @cancelAdd="addVisible = false"
      @success="addSuccess"
    />

    <!--  编辑佣金模板  -->
    <SetCommissionTemplate
      :visible="editTemplateVisible"
      :id="editId"
      :templateId="templateId"
      @handleCancel="handleTemplateCancel"
      @success="handleTemplateSuccess"
    />

    <!--  新增团队成员  -->
    <AddTeamPersonnel
      :visible="addTeamPersonnelVisible"
      :id="editId"
      :teamName="teamName"
      :villageOptions="villageOptions"
      @handleCancel="addTeamPersonnelVisible = false"
      @success="handleAddTeamSuccess"
    />

    <!--   移除团队成员   -->
    <RemoveTeamPersonnel
      :visible="removeTeamPersonnelVisible"
      :id="editId"
      :removeType="removeTeamType"
      @handleCancel="removeTeamPersonnelVisible = false"
      @success="handleRemoveTeamSuccess"
    />
  </div>
</template>

<script>
import {
  reactive,
  ref,
  toRefs,
  computed,
  watch,
  defineComponent,
  createVNode,
} from "vue";
import request from "../../../../common/utils/request";
import { useRoute, useRouter } from "vue-router";
import { TextTip } from "bl-common-vue3";
import store from "@/store";
import { Form, message, Modal } from "ant-design-vue";
const useForm = Form.useForm;
import { ExclamationCircleOutlined, FormOutlined } from "@ant-design/icons-vue";
import AddBusinessTeam from "@/views/village/BusinessManage/modules/AddBusinessTeam.vue";
import SetCommissionTemplate from "@/views/village/BusinessManage/modules/SetCommissionTemplate.vue";
import AddTeamPersonnel from "@/views/village/BusinessManage/modules/AddTeamPersonnel.vue";
import RemoveTeamPersonnel from "@/views/village/BusinessManage/modules/RemoveTeamPersonnel.vue";
import _ from "lodash";
export default defineComponent({
  name: "BusinessTeam",
  props: {
    activeKey: {
      type: [Number, String],
      default: "",
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    AddBusinessTeam,
    FormOutlined,
    SetCommissionTemplate,
    AddTeamPersonnel,
    RemoveTeamPersonnel,
  },
  setup(props, { emit }) {
    const state = reactive({
      dataList: [],
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      addVisible: false,
      editTemplateVisible: false,
      editId: 0,
      addTeamPersonnelVisible: false,
      teamName: "",
      removeTeamPersonnelVisible: false,
      templateId: 0,
      commissionTemplateOptions: [],
      removeTeamType: "",
    });

    const searchParams = reactive({
      name: "",
      leader_name: "",
      template_id: undefined,
      village_id: undefined,
    });

    const { resetFields } = useForm(searchParams, {});

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const getCommissionList = () => {
      request.get("/org", "/business/customer/commissionIndex").then((res) => {
        console.log(res);
        state.commissionTemplateOptions = res?.data.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      });
    };

    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        pageSize: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }

      request
        .post("/org", "/business/customerTeam/list", params)
        .then((res) => {
          state.dataList = res?.list || [];
          state.total = res?.total || 0;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    const addTeam = () => {
      state.editId = 0;
      state.addVisible = true;
    };

    const addSuccess = () => {
      state.addVisible = false;
      getDataList();
    };

    const handleTemplateCancel = () => {
      state.editTemplateVisible = false;
      state.templateId = 0;
      state.editId = 0;
    };

    const handleTemplateSuccess = () => {
      handleTemplateCancel();
      getDataList();
    };

    const handleAddTeamSuccess = () => {
      state.addTeamPersonnelVisible = false;
      getDataList();
    };

    const handleRemoveTeamSuccess = () => {
      state.removeTeamPersonnelVisible = false;
      state.removeTeamType = "";
      getDataList();
    };

    // 编辑佣金模板
    const editTemplate = (record) => {
      state.templateId = record.template_id || 0;
      state.editId = record.id || 0;
      state.editTemplateVisible = true;
    };

    const editTeam = (record) => {
      state.editId = record.id || 0;
      state.addVisible = true;
    };

    const handleAddTeamPersonnel = (record) => {
      state.editId = record.id || 0;
      state.teamName = record.name;
      state.addTeamPersonnelVisible = true;
    };

    const handleRemoveTeamPersonnel = (record) => {
      state.editId = record.id || 0;
      state.removeTeamType = "";
      state.removeTeamPersonnelVisible = true;
    };

    const showTeamUser = (record) => {
      state.editId = record.id || 0;
      state.removeTeamType = "view";
      state.removeTeamPersonnelVisible = true;
    };

    const handleDelete = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要删除该团队吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
            .del("/org", "/business/customerTeam/delete", { id: record.id })
            .then((res) => {
              message.success(res?.msg || "删除成功");
              getDataList();
            });
        },
      });
    };

    const init = () => {
      getCommissionList();
      getDataList(true);
    };

    watch(
      () => props.activeKey,
      (val) => {
        if (val == 2) {
          init();
        }
      },
      { immediate: true }
    );

    const columns = [
      {
        title: "团队名称",
        align: "center",
        dataIndex: "name",
        key: "name",
        fixed: store.getters.isMobile ? undefined : "left",
        width: 200,
      },
      {
        title: "招商经理",
        align: "center",
        dataIndex: "leader_name",
        key: "leader_name",
      },
      {
        title: "团队数量",
        align: "center",
        dataIndex: "team_user_count",
        key: "team_user_count",
      },
      {
        title: "佣金模板",
        align: "center",
        dataIndex: "commission_template",
        key: "commission_template",
      },
      {
        title: "绑定项目",
        align: "center",
        dataIndex: "village_name",
        key: "village_name",
        width: 220,
      },
      {
        title: "创建时间",
        align: "center",
        dataIndex: "created_at",
        key: "created_at",
      },
      {
        title: "操作",
        align: "center",
        dataIndex: "id",
        key: "action",
        width: 280,
        fixed: "right",
      },
    ];

    return {
      ...toRefs(state),
      columns,
      pagination,
      searchParams,
      handleTableChange,
      reset,
      getDataList,
      addTeam,
      addSuccess,
      editTemplate,
      handleTemplateSuccess,
      editTeam,
      handleDelete,
      handleAddTeamPersonnel,
      handleRemoveTeamPersonnel,
      handleAddTeamSuccess,
      handleRemoveTeamSuccess,
      handleTemplateCancel,
      showTeamUser,
    };
  },
});


</script>

<style lang="less" scoped>
.box {
  padding: 0 10px 10px 10px;
  .header-clue {
    padding: 0 14px;
  }
  .header-box {
    background: #fff;
    padding: 14px 10px;
    p {
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }
  .header {
    background-color: rgb(240, 242, 245);
    padding: 16px 10px;

    .num-info {
      color: @primary-color;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }
  .header-content {
    width: 0;
  }
}
:deep(.ant-tabs-content) {
  height: 100%;
}
:deep(.ant-table-title) {
  padding: 0;
}
:deep(.ant-alert-description) {
  font-size: 12px;
  p {
    margin-bottom: 6px;
  }
}
:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
